import React, { Component } from 'react';
import { Card, Form, DatePicker, Input, Button, Upload, Icon } from 'antd';
import moment from 'moment';
import qs from 'qs';
import { addDriver, getDriverDetail } from 'Services/hu.js';
import { getUrl } from 'Services/config.js';

const FormItem = Form.Item;
const { MonthPicker } = DatePicker;
const { TextArea } = Input;

@Form.create()
export default class driverDetails extends Component {
  constructor(props) {
    super(props);
    window.scope = this;
  }

  state = {
    list: {},
    fileList: [
      // {
      //   uid: '-1',
      //   name: 'xxx.png',
      //   status: 'done',
      //   url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
      // },
    ],
  };

  componentDidMount() {
    this.getDriverData();
  }

  getDriverData = async () => {
    const { type, id } = this;
    if (type === 'add') return false;
    const { setFieldsValue } = this.props.form;
    const { data = {} } = (await getDriverDetail({ id })) || {};
    const state = { list: data };
    if (data.photo)
      state.fileList = [
        {
          uid: '-1',
          name: 'xxx.png',
          status: 'done',
          url: data.photo,
          response: {
            photo: data.photo,
          },
        },
      ];
    this.setState(state);
    const { id: _, ...obj } = data;
    obj.age = moment(obj.age);
    if (type === 'edit') setFieldsValue(obj);
  };

  id = qs.parse(this.props.location.search.substr(1)).id;

  type = this.props.match.params.type;

  handleSubmit = e => {
    e.preventDefault();
    const { validateFields } = this.props.form;
    validateFields((err, value) => {
      if (err) return false;
      const { fileList: [{ response: { photo } = {} } = {}] = [] } = this.state;
      const data = {
        ...value,
        age: value.age.format('YYYY-MM'),
      };
      if (photo) data.photo = photo;
      if (this.type === 'edit') data.id = this.id;
      addDriver(data).then(() => {
        this.props.history.goBack();
      });
    });
  };

  handleChange = ({ fileList }) => this.setState({ fileList });

  render() {
    const { type } = this.props.match.params;
    const title = type === 'add' ? '新增司机' : `司机详情(${type === 'edit' ? '编辑' : '查看'})`;
    const isView = type === 'view';
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        span: 8,
      },
      wrapperCol: {
        span: 16,
      },
    };
    const { list, fileList } = this.state;
    const [{ response: { photo } = {} } = {}] = fileList;

    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">Upload</div>
      </div>
    );

    return (
      <Card title={title}>
        <Form onSubmit={this.handleSubmit} style={{ maxWidth: '500px' }}>
          <FormItem label="姓名" {...formItemLayout}>
            {!isView ? (
              getFieldDecorator('name', {
                rules: [{ required: true }],
              })(<Input placeholder="请输入" />)
            ) : (
              <span>{list.name}</span>
            )}
          </FormItem>

          <FormItem label="照片" {...formItemLayout}>
            {!isView ? (
              <Upload
                action={getUrl('/imgupload')}
                listType="picture-card"
                fileList={fileList}
                // onPreview={this.handlePreview}
                onChange={this.handleChange}
              >
                {fileList.length >= 1 ? null : uploadButton}
              </Upload>
            ) : (
              <img alt="暂无" src={photo} width="100px" />
            )}
          </FormItem>

          <FormItem label="出生年月" {...formItemLayout}>
            {!isView ? (
              getFieldDecorator('age', {
                rules: [{ required: true }],
              })(<MonthPicker placeholder="请输入出生日期" />)
            ) : (
              <span>{list.age}</span>
            )}
          </FormItem>

          <FormItem label="联系方式" {...formItemLayout}>
            {!isView ? (
              getFieldDecorator('tel', {
                rules: [{ required: true }, { pattern: /^1[0-9]{10}$/ }],
              })(<Input type="number" placeholder="请输入联系方式" />)
            ) : (
              <span>{list.tel}</span>
            )}
          </FormItem>

          <FormItem label="健康状况" {...formItemLayout}>
            {!isView ? (
              getFieldDecorator('health', {
                rules: [{ required: true }],
              })(<Input placeholder="请输入健康状况" />)
            ) : (
              <span>{list.health}</span>
            )}
          </FormItem>

          <FormItem label="所属线路" {...formItemLayout}>
            {!isView ? (
              getFieldDecorator('line', {
                rules: [{ required: true }],
              })(<Input placeholder="请输入线路" />)
            ) : (
              <span>{list.health}</span>
            )}
          </FormItem>

          <FormItem label="初始密码" {...formItemLayout}>
            {!isView ? (
              getFieldDecorator('password', {
                rules: [{ required: true }],
              })(<Input placeholder="请输入初始密码" />)
            ) : (
              <span>{list.password}</span>
            )}
          </FormItem>

          <FormItem label="驾驶证号" {...formItemLayout}>
            {!isView ? (
              getFieldDecorator('licensecard', {
                rules: [{ required: true }],
              })(<Input placeholder="请输入驾驶证号" />)
            ) : (
              <span>{list.licenseCard}</span>
            )}
          </FormItem>
          <FormItem label="身份证号" {...formItemLayout}>
            {!isView ? (
              getFieldDecorator('idcard', {
                rules: [{ required: true }],
              })(<Input placeholder="请输入身份证号" />)
            ) : (
              <span>{list.idCard}</span>
            )}
          </FormItem>

          <FormItem label="家庭住址" {...formItemLayout}>
            {!isView ? (
              getFieldDecorator('address', {
                rules: [{ required: true }],
              })(<TextArea rows="3" placeholder="请输入家庭住址" />)
            ) : (
              <span>{list.address}</span>
            )}
          </FormItem>

          <FormItem label="准驾车型" {...formItemLayout}>
            {!isView ? (
              getFieldDecorator('permission', {
                // rules: [{ required: true }],
              })(<Input placeholder="请输入准驾车型" />)
            ) : (
              <span>{list.permission}</span>
            )}
          </FormItem>

          <FormItem label="合同日期" {...formItemLayout}>
            {!isView ? (
              getFieldDecorator('cotractcriod', {
                // rules: [{ required: true }],
              })(<Input placeholder="请输入合同日期" />)
            ) : (
              <span>{list.cotractPriod}</span>
            )}
          </FormItem>

          {!isView && (
            <FormItem wrapperCol={{ offset: 8 }}>
              <Button type="primary" htmlType="submit">
                提交
              </Button>
            </FormItem>
          )}
        </Form>
      </Card>
    );
  }
}
